package com.pengliu.config.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.pengliu.common.bean.OssFile;
import com.pengliu.common.bean.OssFileExample;
import com.pengliu.common.bean.SysUser;
import com.pengliu.service.OssFileService;
import com.pengliu.service.SysAuthService;
import com.pengliu.service.SysUserService;
import com.pengliu.service.vo.Menu;
import com.pengliu.util.Constants;
import com.pengliu.util.Lists;
import com.pengliu.util.NetworkUtil;

/**
 * user: pengliu
 * date: 2017年9月29日
 * desc: 登陆成功后操作
 */
@Component
public class SecuritySuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysAuthService sysAuthService;
	
	@Autowired
	private OssFileService ossFileService;
	
	public SecuritySuccessHandler() {
	}

	/**
	 * Constructor which sets the <tt>defaultTargetUrl</tt> property of the base class.
	 * @param defaultTargetUrl the URL to which the user should be redirected on
	 * successful authentication.
	 */
	public SecuritySuccessHandler(String defaultTargetUrl) {
		setDefaultTargetUrl(defaultTargetUrl);
	}
	  
    
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws IOException, ServletException {
		//更新最后登陆时间
		updateSysUserLastTime(request, response, authentication);
		
		super.handle(request, response, authentication);
		
		super.clearAuthenticationAttributes(request);
	}
	
	/**
	 * user: pengliu
	 * date: 2017年9月29日
	 * desc: 更新最后登陆时间
	 * @param request
	 * @param response
	 * @param authentication
	 */
	public void updateSysUserLastTime(HttpServletRequest request, HttpServletResponse response,Authentication authentication) {
		
		SecurityDetails securityDetails = (SecurityDetails) authentication.getPrincipal();
		
		request.getSession().setAttribute(Constants.LOGINROLE, securityDetails.getSysRole());
		
		SysUser sysUser = new SysUser();
		
		BeanUtils.copyProperties(securityDetails, sysUser);
		
		request.getSession().setAttribute(Constants.SESSION_USER, sysUser);
		
		sysUser.setLastTime(new Date());
		
		sysUser.setLoginCount(sysUser.getLoginCount()+1);
		
		String ip = "";
		
		try {
			ip = NetworkUtil.getIpAddress(request);
		} catch (IOException e) {
			ip = "0.0.0.0";
		}
		
		sysUser.setLastIp(ip);
		
		sysUserService.updateByPrimaryKeySelective(sysUser);
		
		//获取菜单集合
		List<Menu> listMenu = new ArrayList<Menu>(); 
		
		if(null != securityDetails.getSysRole()) {
			listMenu = treeMenuList(securityDetails.getSysRole().getId(), sysAuthService.getMenuAll(), 0);
		}
		
		request.getSession().setAttribute(Constants.MENUS, listMenu);
		
		//获取音乐集合
		OssFileExample ossFileExample = new OssFileExample();
		ossFileExample.getCriteria()
			.andSysUserIdEqualTo(sysUser.getId())
			.andContentTypeLike("%audio%");
		List<OssFile> listOssFile = ossFileService.selectByExample(ossFileExample);
		
		List<Map<String,Object>> listMusics = new ArrayList<Map<String,Object>>();
		for (OssFile ossFile : listOssFile) {
			Map<String,Object> music = new HashMap<String,Object>();
			music.put("title", ossFile.getFileTag());
			music.put("artist", "无");
			music.put("mp3", "/ossGet"+ossFile.getFilePath());
			//music.put("poster", "无");
			listMusics.add(music);
		}
		request.getSession().setAttribute(Constants.MUSIC, listMusics);
	}
	
	//菜单树形结构
    public List<Menu> treeMenuList( Integer sysRoleId , List<Menu> menuList, Integer parentId) {
    	List<Menu> childMenu = Lists.newArrayList();
    	for (Menu menu : menuList) {
    		Integer menuId = menu.getId();
    		Integer pid = menu.getPid();
    		menu.setHasQX(sysRoleId.intValue() == menu.getRoleId());
    		if (parentId.intValue() == pid.intValue() && menu.isHasQX()) {
				List<Menu> c_node = treeMenuList(sysRoleId , menuList, menuId);
    			menu.setSubMenu(c_node);
    			childMenu.add(menu);
    		}
		}
        return childMenu;
    }
}
